<script setup>
import { addressDeleteService, addressGetService, addressPostService, addressPutService } from '@/api/address';
import {
  Plus
} from '@element-plus/icons-vue'
import { ref, computed } from 'vue'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  canSelect: { type: Boolean, default: false },
  onSelect: Function
});

const emit = defineEmits(['update:modelValue'])

const showAddressDialog = computed({
  get: () => {
    if (props.modelValue) {
      getUserAddresses();
    }
    return props.modelValue;
  },
  set: (value) => {
    emit('update:modelValue', value)
  }
});
const showAddressForm = ref(false);
const addressFormType = ref('add');

const onSelect = (selectedAddress) => {
  if (props.canSelect) {
    if (props.onSelect) {
      props.onSelect(selectedAddress);
    }
    showAddressDialog.value = false;
  }
}

// 省市区数据
const areaOptions = ref([
  {
    value: '广东省',  // 修改：value与label相同
    label: '广东省',
    children: [
      // 广州市
      {
        value: '广州市',  // 修改
        label: '广州市',
        children: [
          { value: '越秀区', label: '越秀区' },
          { value: '荔湾区', label: '荔湾区' },
          { value: '海珠区', label: '海珠区' },
          { value: '天河区', label: '天河区' },
          { value: '白云区', label: '白云区' },
          { value: '黄埔区', label: '黄埔区' },
          { value: '番禺区', label: '番禺区' },
          { value: '花都区', label: '花都区' },
          { value: '南沙区', label: '南沙区' },
          { value: '增城区', label: '增城区' },
          { value: '从化区', label: '从化区' }
        ]
      },
      // 深圳市
      {
        value: '深圳市',  // 修改
        label: '深圳市',
        children: [
          { value: '罗湖区', label: '罗湖区' },
          { value: '福田区', label: '福田区' },
          { value: '南山区', label: '南山区' },
          { value: '宝安区', label: '宝安区' },
          { value: '龙岗区', label: '龙岗区' },
          { value: '盐田区', label: '盐田区' },
          { value: '龙华区', label: '龙华区' },
          { value: '坪山区', label: '坪山区' },
          { value: '光明区', label: '光明区' }
        ]
      },
      // 其他地级市（全部值改为中文标签）
      {
        value: '珠海市', label: '珠海市',  // 修改
        children: [
          { value: '香洲区', label: '香洲区' },
          { value: '斗门区', label: '斗门区' },
          { value: '金湾区', label: '金湾区' }
        ]
      },
      {
        value: '汕头市', label: '汕头市',  // 修改
        children: [
          { value: '金平区', label: '金平区' },
          { value: '龙湖区', label: '龙湖区' },
          { value: '濠江区', label: '濠江区' },
          { value: '潮阳区', label: '潮阳区' },
          { value: '潮南区', label: '潮南区' },
          { value: '澄海区', label: '澄海区' },
          { value: '南澳县', label: '南澳县' }
        ]
      },
      // 后续所有城市/区县均按此规则修改...
      {
        value: '佛山市', label: '佛山市',
        children: [/* 禅城区/南海区...等 */]  // 子节点需改为中文值
      },
      {
        value: '韶关市', label: '韶关市',
        children: [/* 浈江区/武江区...等 */]
      },
      // ...其他城市结构相同处理（value = label）
      {
        value: '河源市', label: '河源市',  // 修改
        children: [
          { value: '源城区', label: '源城区' },  // 修改
          { value: '东源县', label: '东源县' },
          { value: '和平县', label: '和平县' },
          { value: '龙川县', label: '龙川县' },
          { value: '紫金县', label: '紫金县' },
          { value: '连平县', label: '连平县' }
        ]
      },
      // 处理无子节点的城市（如东莞）
      {
        value: '东莞市', label: '东莞市',  // 修改
        children: []  // 保持空数组
      }
      // ...其他城市同理
    ]
  }
]);

// 用户收货地址
const userAddresses = ref([
]);
const getUserAddresses = async () => {
  const res = await addressGetService();
  userAddresses.value = res.data.data;
}

// 新添加的地址
const newAddress = ref({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: '',
  isDefault: false
});


// 保存新地址
const saveNewAddress = async () => {
  const res = await addressPostService(newAddress.value);
  const id = res.data.data;
  // 如果设置为默认地址
  if (newAddress.value.isDefault) {
    for (const userAddresse of userAddresses.value) {
      if (userAddresse.isDefault = true) {
        userAddresse.isDefault = false;
      }
    }
  }
  userAddresses.value.push({
    ...newAddress.value,
    id
  });
  
  resetNewAddress();
  showAddressForm.value = false;
}

// 更新地址
const updateAddress = async (addressId) => {
  await addressPutService(addressId, newAddress.value);
  showAddressForm.value = false;
}

// 删除地址
const deleteAddress = async (addressId) => {
  await addressDeleteService(addressId);
  userAddresses.value = userAddresses.value.filter(userAddress => userAddress.addressId !== addressId);
}

const handleEditAddress = (address) => {
  newAddress.value = address;
  
  // 根据已有地址初始化选择器
  selectedAreas.value = [];
  const provinceObj = areaOptions.value.find(p => p.label === address.province);
  if (provinceObj) {
    selectedAreas.value.push(provinceObj.value);
    
    const cityObj = provinceObj.children?.find(c => c.label === address.city);
    if (cityObj) {
      selectedAreas.value.push(cityObj.value);
      
      const districtObj = cityObj.children?.find(d => d.label === address.district);
      if (districtObj) {
        selectedAreas.value.push(districtObj.value);
      }
    }
  }
  
  addressFormType.value = 'update';
  showAddressForm.value = true;
};

// 添加selectedAreas响应式变量
const selectedAreas = ref([]);

// 处理地区选择变化
const handleAreaChange = (value) => {
  if (value.length === 3) {
    const [province, city, district] = value;
    newAddress.value.province = areaOptions.value
      .find(p => p.value === province)?.label || '';
      
    newAddress.value.city = areaOptions.value
      .find(p => p.value === province)
      ?.children?.find(c => c.value === city)?.label || '';
      
    newAddress.value.district = areaOptions.value
      .find(p => p.value === province)
      ?.children?.find(c => c.value === city)
      ?.children?.find(d => d.value === district)?.label || '';
  }
};

// 重置新地址表单
const resetNewAddress = () => {
  newAddress.value = {
    receiverName: '',
    receiverPhone: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    isDefault: false
  };
  selectedAreas.value = []; // 重置选择器
}
</script>

<template>
  <div>
    <el-dialog
      v-model="showAddressDialog" 
      title="管理收货地址"
      width="50%"
      class="address-dialog"
    >
      <div class="address-container">
        <el-button type="primary" :icon="Plus" @click="resetNewAddress(); addressFormType = 'add';showAddressForm = true;">添加新地址</el-button>
        
        <div class="address-list">
          <div 
            v-for="userAddress in userAddresses"
            :key="userAddress.addressId"
            class="address-item"
            :class="{'can-select-address-item' : canSelect }"
            @click="onSelect(userAddress)"
          >
            <div class="address-info">
              <div class="address-header">
                <span class="name">{{ userAddress.receiverName }}</span>
                <span class="phone">{{ userAddress.receiverPhone }}</span>
                <el-tag type="danger" size="small" v-if="userAddress.isDefault">默认地址</el-tag>
              </div>
              <div class="address-detail">
                {{ userAddress.province }}{{ userAddress.city }}{{ userAddress.district }}{{ userAddress.detailAddress }}
              </div>
            </div>
            <div class="address-actions">
              <el-button text @click="handleEditAddress(userAddress)">编辑</el-button>
              <el-button type="danger" text @click="deleteAddress(userAddress.addressId)">删除</el-button>
              <el-button type="primary" text v-if="!userAddress.isDefault" @click="userAddress.isDefault = true">设为默认</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog 
      v-model="showAddressForm" 
      :title="addressFormType === 'add' ? '添加新地址' : '更新地址'"
      width="500px"
    >
      <el-form :model="newAddress" label-width="80px">
        <el-form-item label="收货人" required>
          <el-input v-model="newAddress.receiverName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" required>
          <el-input v-model="newAddress.receiverPhone" placeholder="请输入收货人手机号" />
        </el-form-item>
        <el-form-item label="所在地区" required>
          <el-cascader 
            v-model="selectedAreas" 
            :options="areaOptions" 
            placeholder="请选择省/市/区"
            style="width: 100%"
            :props="{
              expandTrigger: 'hover',
              value: 'value',
              label: 'label',
              children: 'children'
            }"
            @change="handleAreaChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" required>
          <el-input 
            v-model="newAddress.detailAddress" 
            type="textarea" 
            placeholder="请输入详细地址信息" 
            :rows="2"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="newAddress.isDefault">设置为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddressForm = false">取消</el-button>
        <el-button type="primary" @click="addressFormType === 'add' ? saveNewAddress() : updateAddress(newAddress.addressId)">保存地址</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>

.address-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
  }
  
  .address-container {
    .el-button {
      margin-bottom: 20px;
    }
    
    .address-list {
      max-height: 400px;
      overflow-y: auto;
      
      .can-select-address-item {
        cursor: pointer;

        &:hover {
          background-color: #dcdcdc21;
        }
      }

      .address-item {
        display: flex;
        justify-content: space-between;
        padding: 15px;
        border-bottom: 1px solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .address-info {
          flex: 1;
          
          .address-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 8px;
            
            .name {
              font-weight: bold;
            }
            
            .el-tag {
              height: 22px;
              line-height: 20px;
            }
          }
          
          .address-detail {
            color: #666;
            font-size: 14px;
          }
        }
        
        .address-actions {
          margin-left: 20px;
        }
      }
    }
  }
}
</style>